﻿namespace Anley.DomainDrivenDesign.Contract.Swagger;

/// <summary>
/// 隐藏Swagger接口过滤器
/// </summary>
internal class HiddenApiFilter
    : IDocumentFilter
{
    /// <summary>
    /// 应用
    /// </summary>
    /// <param name="swaggerDoc"></param>
    /// <param name="context"></param>
    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
    {
        foreach (var apiDescription in context.ApiDescriptions)
        {
            if (!apiDescription.TryGetMethodInfo(out var method))
                continue;

            if (method.ReflectedType == null)
                continue;

            if (method.ReflectedType.CustomAttributes.All(
                t => t.AttributeType != typeof(HiddenApiAttribute))
                && method.CustomAttributes.All(t => t.AttributeType != typeof(HiddenApiAttribute)))
                continue;

            var key = "/" + apiDescription.RelativePath;
            if (key.Contains("?"))
            {
                var idx = key.IndexOf("?", StringComparison.Ordinal);
                key = key[..idx];
            }
            swaggerDoc.Paths.Remove(key);
        }
    }
}